import {Button, Form, Input, message, Modal, Select, Table} from "antd";
import React, {useEffect, useState} from "react";
import type {ColumnsType} from "antd/es/table";
import {
    DeleteTwoTone,
    EditTwoTone,
    ExclamationCircleOutlined,
    SearchOutlined,
} from "@ant-design/icons";
import {
    delAllDepartment,
    delDepartment, editDepartment,
    getDepartmentList,
    getDepartmentSearch
} from "../../api/hisComprehensive/hisApi.ts";
import publicStyle from '../../assets/css/public.module.css'
import style from '../../assets/css/hosComprehensive/hosDepartment.module.css'
import {getAllDoctor} from "../../api/publicApi/publicApi.ts";
import {IDoctor, IOption} from "../../types/publicType/public.ts";
import {departmentNameRules, mainDoctorRules, MODAL_WIDTH} from "../../utils/publicStyleAndRules.ts";

const {confirm} = Modal;

interface DataType {
    key: React.Key;
    id: number;
    createtime: string;
    name: string;
    maindoctor: string;
}

// 日期时间格式化函数
function formatDate(date: any, format = 'yyyy-MM-dd HH:mm:ss') {
    // 确保传入的是日期对象
    const d = date instanceof Date ? date : new Date(date);

    // 定义格式化函数
    const formatDatePart = (value: any, length: any) => {
        let str = String(value);
        while (str.length < length) {
            str = '0' + str;
        }
        return str;
    };

    // 替换格式化字符串中的标记
    return format.replace(/yyyy|MM|dd|HH|mm|ss/g, part => {
        switch (part) {
            case 'yyyy':
                return formatDatePart(d.getFullYear(), 4);
            case 'MM':
                return formatDatePart(d.getMonth() + 1, 2);
            case 'dd':
                return formatDatePart(d.getDate(), 2);
            case 'HH':
                return formatDatePart(d.getHours(), 2);
            case 'mm':
                return formatDatePart(d.getMinutes(), 2);
            case 'ss':
                return formatDatePart(d.getSeconds(), 2);
            default:
                return part;
        }
    });
}

export default function DepartmentManagement() {
    // 表格列
    const columns: ColumnsType<DataType> = [
        {
            title: '科室编号',
            dataIndex: 'id',
            key: 'id',
        },
        {
            title: '科室创建时间',
            dataIndex: 'createtime',
            key: 'createtime',
            render: (text) => formatDate(text)
        },
        {
            title: '科室名称',
            dataIndex: 'name',
            key: 'name',
        },
        {
            title: '科室主任',
            dataIndex: 'maindoctor',
            key: 'maindoctor',
        },
        {
            title: '科室操作',
            key: Date.now().toString(),
            render: (_, record) =>
                <div className={style.operation}>
                    <DeleteTwoTone className={style.btn} onClick={() => handleDelClick([record.id], 'single')}/>
                    <EditTwoTone className={style.btn} onClick={() => showModal(record)}/>
                </div>,
        },
    ];

    // 查询表单
    const [dataForm] = Form.useForm();

    // 详情表单
    const [infoForm] = Form.useForm();

    // 表格数据
    const [data, setData] = useState<DataType[]>([]);

    // 选中的表格行id
    const [selectIds, setIds] = useState<number[]>([]);

    // module显隐
    const [isModalOpen, setIsModalOpen] = useState<boolean>(false);

    // 下拉框列表
    const [options, setOptions] = useState<IOption[]>([]);

    // 表格分页
    const [pagination, setPagination] = useState({
        page: 1,
        size: 16,
        total: 0,
    });

    // 复选框操作
    const rowSelection = {
        onChange: (selectedRowKeys: React.Key[]) => {
            setIds(selectedRowKeys);
        },
    };

    // 处理删除挂号
    const handleDelDepartment = async (id: number) => {
        const res = await delDepartment({id});
        if (res) {
            dataForm.getFieldsValue() ? await handleGetDepartmentSearch(dataForm.getFieldsValue().partName) : await handleGetDepartmentList()
        }
    }

    // 处理批量删除挂号
    const handleAllDelDepartment = async (ids: any) => {
        const res = await delAllDepartment({ids: JSON.stringify([ids])});
        if (res) {
            setIds([]);
            dataForm.getFieldsValue() ? await handleGetDepartmentSearch(dataForm.getFieldsValue().partName) : await handleGetDepartmentList()
        }
    }

    // 获取列表数据
    const handleGetDepartmentList = async () => {
        const res = await getDepartmentList({page: pagination.page, size: pagination.size});
        if (res) {
            setData(res.data)
            setPagination({...pagination, total: res.total});
        }
    }

    // 获取所有医生数据
    const handelGetAllDoctor = async () => {
        const res = await getAllDoctor();
        if (res) {
            const data = res.data.map((item: IDoctor) => {
                return {
                    label: item.name,
                    value: item.name
                }
            });
            setOptions(data)
        }
    }

    // 查询科室
    const handleGetDepartmentSearch = async (params: string) => {
        const res = await getDepartmentSearch({page: pagination.page, size: pagination.size, name: params})
        if (res) {
            setData(res.data)
            setPagination({...pagination, total: res.total});
        }
    }

    // 修改科室数据
    const handelEditDepartment = async (params: DataType) => {
        const res = await editDepartment(params)
        if (res) {
            await handleGetDepartmentList()
        }
    }

    useEffect((): void => {
        handleGetDepartmentList()
    }, []);

    // 提交查询表单
    const onFinish = async (values: any) => {
        await handleGetDepartmentSearch(values.partName)
    };

    // 展示model
    const showModal = async (param: DataType) => {
        infoForm.setFieldsValue(param)
        await handelGetAllDoctor()
        setIsModalOpen(true);
    };

    // 确认按钮点击事件
    const handleOk = async () => {
        await handelEditDepartment(infoForm.getFieldsValue())
        setIsModalOpen(false);
    };

    //  取消按钮点击事件
    const handleCancel = () => {
        setIsModalOpen(false);
    };

    /**
     * 删除功能点击事件
     * @param ids 要删除的id/ids
     * @param type 删除的类型：multiple-删除多个，single-删除一个
     */
    const handleDelClick = (ids: number[], type: string) => {
        confirm({
            title: '系统提示',
            icon: <ExclamationCircleOutlined/>,
            content: '您正在进行科室删除操作,此操作不可逆，确定删除吗？',
            okText: '确认删除',
            okType: 'danger',
            cancelText: '取消',
            width: MODAL_WIDTH,
            async onOk() {
                if (type === 'single') {
                    await handleDelDepartment(ids[0])
                }
                if (type === 'multiple') {
                    await handleAllDelDepartment(ids)
                }
            },
            onCancel() {
                message.error('用户取消删除')
            },
        });
    };

    return (
        <div className={publicStyle.container}>
            {/*查询框*/}
            <div className={publicStyle.search}>
                <Form
                    layout={'inline'}
                    form={dataForm}
                    colon={false}
                    onFinish={onFinish}
                >
                    <Form.Item label="科室名称" name="partName">
                        <Input prefix={<SearchOutlined/>} placeholder="输入科室名称"
                               className={publicStyle.searchInput}/>
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" htmlType="submit" icon={<SearchOutlined/>}>
                            查询
                        </Button>
                    </Form.Item>
                </Form>
                <Button type="default" onClick={() => handleDelClick(selectIds, 'multiple')}>删除选中</Button>
            </div>

            {/*表格*/}
            <div className={publicStyle.content}>
                <Table
                    rowKey={record => record.id}
                    rowSelection={{
                        type: 'checkbox',
                        ...rowSelection,
                    }}
                    size="small"
                    columns={columns}
                    dataSource={data}
                    pagination={{position: ['bottomLeft'], showSizeChanger: true, showQuickJumper: true}}
                />
            </div>

            {/*弹出框*/}
            <div>
                <Modal
                    title="编辑科室"
                    onOk={handleOk}
                    open={isModalOpen}
                    onCancel={handleCancel}
                    width={MODAL_WIDTH}
                    closable={false}
                    maskClosable={false}
                >
                    <Form
                        form={infoForm}
                        colon={false}
                        requiredMark={false}
                    >
                        <Form.Item label="科室名称" name="name" rules={departmentNameRules}>
                            <Input placeholder="输入科室名称"/>
                        </Form.Item>
                        <Form.Item label="科室主任" name="maindoctor" rules={mainDoctorRules}>
                            <Select
                                options={options}
                            />
                        </Form.Item>
                        <Form.Item label="创建时间" name="createtime">
                            <Input disabled placeholder="输入创建时间"/>
                        </Form.Item>
                        <Form.Item label="科室编号" name="id">
                            <Input disabled placeholder="输入科室编号"/>
                        </Form.Item>
                    </Form>
                </Modal>
            </div>
        </div>
    )
}
